﻿using Microsoft.Extensions.Logging;
using XYAC.Framework.WohuaMesExtend.IHI.LocalData.Context;
using XYAC.Framework.WohuaMesExtend.IHI.LocalData.Models;
using XYAC.Framework.WohuaMesExtend.IHI.OracleRemoteDB;

namespace XYAC.Framework.WohuaMesExtend.IHI.Services
{
    internal class HyperDbService
    {

        private const string __REMOTE_SYNC_STATE_PENDING = "PENDING";
        private const string __REMOTE_SYNC_STATE_COMPLETE = "COMPLETE";
        public HyperDbService(LocalDataContext localDataContext, OracleMesContext oracleMesContext, ILogger<HyperDbService> logger)
        {
            this.LocalDb = localDataContext;
            this.MesDb = oracleMesContext;
            this.Logger = logger;
        }

        public LocalDataContext LocalDb { get; }
        public OracleMesContext MesDb { get; }
        public ILogger<HyperDbService> Logger { get; }

        /// <summary>
        /// 将中间表数据同步到远程服务器,并且将数据状态更新为Pending
        /// </summary>
        /// <param name="inspectList"></param>
        /// <returns></returns>
        public int SyncInspectData(IEnumerable<OracleRemoteDB.YB_LOT_INSPECT> inspectList)
        {
            var ret = 0;
            foreach (var inspect in inspectList)
                inspect.RECEIVE_FLAG = __REMOTE_SYNC_STATE_COMPLETE;

            using (var localTrans = this.LocalDb.Database.BeginTransaction())
            {
                using (var remoteTrans = this.MesDb.Database.BeginTransaction())
                {
                    try
                    {
                        this.LocalDb.YB_LOT_INSPECT.AddRange(inspectList.Select(T => YB_LOT_INSPECT_Local.ConvertToLocal(T)).ToList());
                        this.MesDb.YB_LOT_INSPECT.UpdateRange(inspectList);
                        var mesUpdateRet = this.MesDb.SaveChanges();
                        var localInsertRet = this.LocalDb.SaveChanges();
                        if (mesUpdateRet == localInsertRet)
                        {
                            localTrans.Commit();
                            remoteTrans.Commit();
                            ret = mesUpdateRet;
                        }
                        else
                        {
                            localTrans.Rollback();
                            remoteTrans.Rollback();
                        }
                    }
                    catch (Exception ex)
                    {

                        localTrans.Rollback();
                        remoteTrans.Rollback();
                        Logger.LogError("同步中间表条码数据失败!", ex);
                    }
                }
            }
            return ret;
        }
    }
}
